package cn.chy.com.springbootdemo2.advice;

import cn.chy.com.springbootdemo2.base.annotation.IgnoreCommonResponseAnnotation;
import cn.chy.com.springbootdemo2.vo.CommonsResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description: TODO
 * @author: 颜景琦
 * @date: 2021年10月25日 11:56
 */
// 在程序之前执行增强
@RestControllerAdvice(value = "cn.chy.com.springbootdemo2.controller")
public class CommonResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 内部封装
        if (!returnType.getDeclaringClass().isAnnotationPresent(IgnoreCommonResponseAnnotation.class)
                && !returnType.getMethod().isAnnotationPresent(IgnoreCommonResponseAnnotation.class)) {
            return true;
        }
        return false;
    }

    // 在返回响应之前，做一次封装（将控制层的返回结果同一返回到CommonsResponse）
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if (null == body)
            return CommonsResponse.builder().code(200).message("成功").data(null).build();
        else if (body instanceof CommonsResponse)
            return (CommonsResponse) body;

        return CommonsResponse.builder().code(200).message("成功").data(body).build();
    }
}
